package com.gyj.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/*
 * 解析token+校验uri
 */
@Slf4j
@Component
public class RepeatedSubmitFilter implements GlobalFilter, Ordered {

	private static final String UNKNOWN = "unknown";
	@Resource
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public int getOrder() {
		return 1;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		ServerHttpRequest request = exchange.getRequest();
		String method = request.getMethodValue();
		//GET请求不用防重
		if("GET".equals(method)){
			return chain.filter(exchange);
		}
		// X-Forwarded-For：Squid 服务代理
		String ipAddresses = request.getHeaders().getFirst("X-Forwarded-For");
		if (ipAddresses == null || ipAddresses.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
			// Proxy-Client-IP：apache 服务代理
			ipAddresses = request.getHeaders().getFirst("Proxy-Client-IP");
		}
		if (ipAddresses == null || ipAddresses.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
			// WL-Proxy-Client-IP：weblogic 服务代理
			ipAddresses = request.getHeaders().getFirst("WL-Proxy-Client-IP");
		}
		if (ipAddresses == null || ipAddresses.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
			// HTTP_CLIENT_IP：有些代理服务器
			ipAddresses = request.getHeaders().getFirst("HTTP_CLIENT_IP");
		}
		if (ipAddresses == null || ipAddresses.length() == 0 || UNKNOWN.equalsIgnoreCase(ipAddresses)) {
			// X-Real-IP：nginx服务代理
			ipAddresses = request.getHeaders().getFirst("X-Real-IP");
		}
		String ip;
		if(Objects.isNull(ipAddresses)){
			ip=Objects.requireNonNull(request.getRemoteAddress()).getAddress().toString();
		}else{
			if (ipAddresses.contains(",")){
				ip=ipAddresses.split(",")[0];
			}else{
				ip=ipAddresses;
			}
		}
		String key="banksteel:uaa:repeat-submit:"+method+":"+ip+":"+request.getURI().getPath();
		String value=stringRedisTemplate.opsForValue().get(key);
		log.info("访问的的key={},value={}",key,value);
		if(StringUtils.equals("1",value)){
			ServerHttpResponse response=  exchange.getResponse();
			response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
			response.setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
			DataBuffer dataBuffer = response.bufferFactory().wrap("您的请求过于频繁，请稍后再试".getBytes(StandardCharsets.UTF_8));
			return response.writeWith(Mono.just(dataBuffer));
		}
		stringRedisTemplate.opsForValue().set(key,"1",200, TimeUnit.MILLISECONDS);
		return chain.filter(exchange);
	}

}
